package server.main.utils.mainutils;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ymlUtils {
    /**
     * 解析yml获取yml的配置信息
     * @param filepath 文件路径
     * @return
     */
    public static Map getyml(String filepath){
        FileInputStream fileInputStream = null;
        try {
            Yaml yaml = new Yaml();//实例化解析器
//            System.out.println(1);
            File file = new File(filepath);//配置文件地址
//            System.out.println(2);
            try {
                fileInputStream = new FileInputStream(file);
//                System.out.println(3);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Map map = yaml.loadAs(fileInputStream, Map.class);
//            printMap(map, 0);
            return map;
        }catch(Exception e) {

            e.printStackTrace();
        }finally {
            try {
                if(fileInputStream!=null)
                    fileInputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void printMap(Map map, int count){
        Set set = map.keySet();
        for(Object key: set){

            Object value = map.get(key);

            for(int i=0; i<count; i++){
                System.out.print("    ");
            }

            if(value instanceof Map) {

                System.out.println(key+":");
//                System.out.println("Map(value)+"+(Map)value);
                printMap((Map)value, count+1);//嵌套
            }else if(value instanceof List){

                System.out.println(key+":");
                for(Object obj: (List)value){
                    for(int i=0; i<count; i++){
                        System.out.print("    ");
                    }
                    System.out.println("    - "+obj.toString());
                }
            }else{

                System.out.println(key + ": " + value);
            }
        }
    }

    /**
     * 获取整个项目的数据库的配置信息
     * @param filepath
     * @return
     */
    public static Map getDatasource(String filepath){
        Map map = getyml(filepath);
        return (Map) ((Map) map.get("spring")).get("datasource");
    }


//    public static void main(String[] args) {

//        Map Mainmap = getDatasource(getyml("C:\\Users\\MingHs\\Desktop\\1\\src\\main\\java\\com\\main\\utils\\application.yml"));

//        System.out.println(Mainmap);
//    }

}
